package com.senior.springaicomposite.controller;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

/**
 * AI对话服务控制器
 * 提供基于不同大模型的对话接口
 */
@RestController
@RequestMapping("/api/ai")
@Slf4j
public class ChatController {

    @Resource(name = "deepseek")
    private ChatClient deepSeekChatClient;

    @Resource(name = "zhipu")
    private ChatClient zhipuAiChatClient;

    /**
     * 通用对话接口
     *
     * @param client 客户端标识 (deepseek|zhipu)
     * @param prompt 用户输入提示
     * @return 对话响应结果
     */
    @GetMapping("/chat/{client}")
    public String chat(@PathVariable String client, @RequestParam String prompt) {
        ChatClient chatClient = "deepseek".equalsIgnoreCase(client) ? deepSeekChatClient : zhipuAiChatClient;

        if (chatClient == null) {
            log.error("未找到对应的AI客户端: {}", client);
            return "系统错误：AI客户端未找到";
        }

        try {
            String response = chatClient.prompt(prompt).call().chatResponse().getResult().getOutput().getText();
            log.info("{} 响应: {}", client, response);
            return response;
        } catch (Exception e) {
            log.error("对话服务异常", e);
            return "对话服务暂时不可用，请稍后重试";
        }
    }

    /**
     * 流式对话接口
     *
     * @param client 客户端标识 (deepseek|zhipu)
     * @param prompt 用户输入提示
     * @return 流式响应结果
     */
    @GetMapping(value = "/stream/{client}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> streamChat(@PathVariable String client, @RequestParam String prompt, HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8"); // 显式设置字符编码

        ChatClient chatClient = "deepseek".equalsIgnoreCase(client) ? deepSeekChatClient : zhipuAiChatClient;
        if (chatClient == null) {
            log.error("未找到对应的AI客户端: {}", client);
            return Flux.just("data: 系统错误：AI客户端未找到\n\n");
        }

        return chatClient.prompt(prompt)
                .stream()
                .content()
                .map(data -> "data: " + data + "\n\n")
                .onErrorResume(e -> {
                    log.error("流式对话服务异常", e);
                    return Flux.just("data: 服务异常，请检查网络或稍后重试\n\n");
                });
    }

}